<?php
/**
 * 文章编辑页面文件
 * 这个页面用于编辑已经发布的博客文章
 * 包含文章标题、内容、分类、标签、图片等信息的修改功能
 * 只有文章作者本人才能编辑自己的文章
 */

// 引入系统初始化文件，包含所有必要的类和函数
require_once '../includes/init.php';

// 检查用户是否已经登录，未登录用户无法编辑文章
if (!isLoggedIn()) {
    // 跳转到登录页面
    redirect('../login.php');
}

// 获取当前登录用户的完整信息
$currentUser = getCurrentUser();

// 从URL参数中获取要编辑的文章ID
// 使用(int)强制转换确保ID是整数类型，防止SQL注入
$articleId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// 验证文章ID是否有效
if ($articleId <= 0) {
    // ID无效，跳转到文章管理页面
    redirect('articles.php');
}

// 根据文章ID从数据库获取文章的详细信息
$article = $blog->getArticleById($articleId);

// 检查文章是否存在且属于当前登录用户
// 这是安全检查，确保用户只能编辑自己的文章
if (!$article || $article['用户ID'] != $currentUser['id']) {
    // 文章不存在或不属于当前用户，跳转到文章管理页面
    redirect('articles.php');
}

// 从数据库获取所有可用的分类列表，用于下拉选择
$categories = $blog->getCategories();
// 从数据库获取所有可用的标签列表，用于下拉选择
$tags = $blog->getTags();

// 获取当前文章已关联的分类和标签
$currentCategories = $blog->getArticleCategories($articleId);
$currentTags = $blog->getArticleTags($articleId);

// 将分类和标签转换为ID数组，用于在表单中预选中相应选项
$currentCategoryIds = array();  // 存储当前文章的分类ID
$currentTagIds = array();       // 存储当前文章的标签ID

// 遍历当前文章的分类，提取ID
foreach ($currentCategories as $category) {
    $currentCategoryIds[] = $category['id'];
}

// 遍历当前文章的标签，提取ID
foreach ($currentTags as $tag) {
    $currentTagIds[] = $tag['id'];
}

// 初始化消息变量，用于显示操作结果
$message = '';      // 消息内容
$messageType = '';  // 消息类型（success/error/info）

// 处理文章更新请求
// isPost()检查是否为POST请求，getPost()获取POST数据并验证
if (isPost() && !empty(getPost('title')) && !empty(getPost('content'))) {
    // 验证CSRF令牌，防止跨站请求伪造攻击
    if (!verifyCSRFToken(getPost('csrf_token'))) {
        // CSRF验证失败，设置错误消息
        $message = 'CSRF验证失败，请重新提交';
        $messageType = 'error';
    } else {
        // CSRF验证通过，开始处理更新数据
        
        // 获取表单提交的基本数据
        $title = getPost('title');           // 文章标题
        $content = getPost('content');       // 文章内容
        
        // 处理复选框数据，如果选中返回1，否则返回0
        $isTop = isset($_POST['is_top']) ? 1 : 0;           // 是否置顶
        $isRecommend = isset($_POST['is_recommend']) ? 1 : 0; // 是否推荐
        
        // 获取选中的分类和标签，如果没有选择则返回空数组
        $selectedCategories = getPost('categories', []);
        $selectedTags = getPost('tags', []);
        
        // 处理图片更新功能
        $imagePath = $article['图片']; // 默认保持原有图片路径
        
        // 检查是否有新的图片上传
        if (isset($_FILES['article_image']) && $_FILES['article_image']['error'] !== UPLOAD_ERR_NO_FILE) {
            // 使用BlogSystem类的uploadImage方法处理新图片上传
            $uploadResult = $blog->uploadImage($_FILES['article_image']);
            
            // 检查上传是否成功
            if ($uploadResult['success']) {
                // 上传成功，更新图片路径
                $imagePath = $uploadResult['path'];
            } else {
                // 上传失败，设置错误消息
                $message = '图片上传失败：' . $uploadResult['error'];
                $messageType = 'error';
            }
        }
        
        // 验证必填字段是否为空
        if (empty($title) || empty($content)) {
            $message = '请填写文章标题和内容';
            $messageType = 'error';
        } elseif (!$message) { 
            // 只有在没有上传错误时才继续更新文章
            
            // 准备要更新到数据库的文章数据数组
            $articleData = [
                'title' => $title,                    // 文章标题
                'content' => $content,                // 文章内容
                'is_top' => $isTop,                   // 是否置顶
                'is_recommend' => $isRecommend,       // 是否推荐
                'image' => $imagePath,                // 文章图片路径
                'categories' => $selectedCategories,  // 选中的分类
                'tags' => $selectedTags              // 选中的标签
            ];
            
            // 调用BlogSystem类的updateArticle方法更新文章
            // 返回true表示更新成功，false表示失败
            $result = $blog->updateArticle($articleId, $articleData);
            
            // 检查文章是否更新成功
            if ($result) {
                // 更新成功，设置成功消息
                $message = '文章更新成功！';
                $messageType = 'success';
                
                // 重新从数据库获取更新后的文章信息
                $article = $blog->getArticleById($articleId);
                
                // 更新成功后自动跳转到文章详情页面
                redirect("../article.php?id=$articleId");
            } else {
                // 更新失败，设置错误消息
                $message = '文章更新失败，请稍后重试';
                $messageType = 'error';
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑文章 - <?php echo escape($article['标题']); ?></title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: "Microsoft YaHei", Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        
        .container {
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
        }
        
        header {
            background: #fff;
            padding: 20px 0;
            margin-bottom: 30px;
            box-shadow: 0 8px 30px rgba(0,0,0,0.12);
            border-radius: 15px;
        }
        
        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .logo {
            font-size: 24px;
            font-weight: bold;
            color: #2c3e50;
        }
        
        .nav {
            display: flex;
            gap: 20px;
        }
        
        .nav a {
            text-decoration: none;
            color: #333;
            padding: 8px 15px;
            border-radius: 5px;
            transition: background-color 0.3s;
        }
        
        .nav a:hover {
            background-color: #3498db;
            color: white;
        }
        
        .edit-container {
            background: white;
            padding: 40px;
            border-radius: 20px;
            box-shadow: 0 15px 50px rgba(0,0,0,0.2);
            position: relative;
            overflow: hidden;
        }
        
        .edit-container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 6px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .edit-header {
            margin-bottom: 30px;
            border-bottom: 2px solid #e1e1e1;
            padding-bottom: 20px;
            padding-left: 20px;
        }
        
        .edit-title {
            font-size: 28px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin-bottom: 10px;
            font-weight: 700;
        }
        
        .user-info {
            color: #666;
            font-size: 14px;
        }
        
        .form-group {
            margin-bottom: 25px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
        }
        
        .required {
            color: #e74c3c;
        }
        
        .form-control {
            width: 100%;
            padding: 15px 20px;
            border: 2px solid #e1e1e1;
            border-radius: 12px;
            font-size: 16px;
            transition: all 0.3s ease;
            font-family: inherit;
            background: #f8f9fa;
        }
        
        .form-control:focus {
            outline: none;
            border-color: #667eea;
            background: white;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            transform: translateY(-2px);
        }
        
        .form-control.textarea {
            resize: vertical;
            min-height: 300px;
            font-family: 'Courier New', monospace;
            line-height: 1.6;
        }
        
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
        }

        @media (max-width: 768px) {
            .form-row {
                grid-template-columns: 1fr;
                gap: 20px;
            }
        }
        
        .checkbox-group {
            border: 2px solid #e1e1e1;
            border-radius: 12px;
            padding: 20px;
            background: #f8f9fa;
            transition: all 0.3s ease;
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-top: 10px;
        }

        .checkbox-group:hover {
            border-color: #667eea;
            background: white;
        }
        
        .checkbox-item {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 12px;
            border-radius: 8px;
            transition: background-color 0.3s;
            cursor: pointer;
        }

        .checkbox-item:hover {
            background-color: rgba(102, 126, 234, 0.1);
        }
        
        .checkbox-item input[type="checkbox"] {
            transform: scale(1.2);
        }
        
        .select-group {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            border: 2px solid #e1e1e1;
            border-radius: 12px;
            padding: 20px;
            min-height: 150px;
            max-height: 200px;
            overflow-y: auto;
            background: #f8f9fa;
            transition: all 0.3s ease;
        }
        
        .select-group:hover {
            border-color: #667eea;
            background: white;
        }
        
        .select-item {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 12px;
            border-radius: 8px;
            transition: background-color 0.3s;
            cursor: pointer;
            white-space: nowrap;
            flex-shrink: 0;
        }

        .select-item:hover {
            background-color: rgba(102, 126, 234, 0.1);
        }
        
        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 30px;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
        }
        
        .btn-warning {
            background: #f39c12;
        }
        
        .btn-warning:hover {
            background: #e67e22;
        }
        
        .btn-secondary {
            background: #95a5a6;
        }
        
        .btn-secondary:hover {
            background: #7f8c8d;
        }
        
        .form-actions {
            display: flex;
            gap: 15px;
            margin-top: 30px;
            padding-top: 25px;
            border-top: 1px solid #e1e1e1;
        }
        
        .alert {
            padding: 12px 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        
        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .help-text {
            font-size: 14px;
            color: #666;
            margin-top: 5px;
        }
        
        .char-count {
            text-align: right;
            font-size: 12px;
            color: #999;
            margin-top: 5px;
        }
        
        .image-preview {
            margin-top: 15px;
            text-align: center;
        }
        
        .image-preview img {
            max-width: 300px;
            max-height: 200px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .image-preview .remove-image {
            display: inline-block;
            margin-top: 10px;
            color: #e74c3c;
            cursor: pointer;
            font-size: 14px;
        }
        
        .image-preview .remove-image:hover {
            text-decoration: underline;
        }

        /* 文件上传样式 */
        .file-upload {
            position: relative;
            display: inline-block;
            cursor: pointer;
            width: 100%;
        }

        .file-upload input[type="file"] {
            position: absolute;
            opacity: 0;
            width: 100%;
            height: 100%;
            cursor: pointer;
        }

        .file-upload-label {
            display: block;
            padding: 20px;
            border: 2px solid #e1e1e1;
            border-radius: 12px;
            text-align: center;
            transition: all 0.3s ease;
            background: #f8f9fa;
            cursor: pointer;
        }

        .file-upload:hover .file-upload-label {
            border-color: #667eea;
            background: white;
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.1);
        }
    </style>
</head>
<body>
    <header>
        <div class="container">
            <div class="header-content">
                <div class="logo">我的博客系统</div>
                <nav class="nav">
                    <a href="../index.php">首页</a>
                    <a href="index.php">管理后台</a>
                    <a href="post.php">发布文章</a>
                    <a href="articles.php">管理文章</a>
                    <a href="../logout.php">退出登录</a>
                </nav>
            </div>
        </div>
    </header>

    <div class="container">
        <div class="edit-container">
            <header class="edit-header">
                <h1 class="edit-title">编辑文章</h1>
                <div class="user-info">
                    当前用户：<?php echo escape($currentUser['用户名']); ?> | 
                    创建时间：<?php echo formatDate($article['创建时间']); ?>
                </div>
            </header>
            
            <?php if (!empty($message)): ?>
                <div class="alert alert-<?php echo $messageType; ?>">
                    <?php echo escape($message); ?>
                </div>
            <?php endif; ?>
            
            <form method="POST" enctype="multipart/form-data">
                <?php csrfField(); ?>
                
                <div class="form-group">
                    <label for="title">文章标题 <span class="required">*</span></label>
                    <input type="text" id="title" name="title" class="form-control" 
                           value="<?php echo escape($article['标题']); ?>" 
                           placeholder="请输入文章标题" required maxlength="200">
                    <div class="help-text">标题长度不超过200个字符</div>
                </div>
                
                <div class="form-group">
                    <label for="article_image">文章图片</label>
                    <?php if (!empty($article['图片'])): ?>
                        <div class="current-image" style="margin-bottom: 15px;">
                            <img src="../<?php echo escape($article['图片']); ?>" alt="当前图片" style="max-width: 300px; max-height: 200px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                            <p style="margin: 10px 0; color: #666; font-size: 14px;">当前图片（选择新图片将替换此图片）</p>
                        </div>
                    <?php endif; ?>
                    <div class="file-upload">
                        <input type="file" id="article_image" name="article_image" 
                               accept="image/jpeg,image/jpg,image/png,image/gif,image/webp">
                        <label for="article_image" class="file-upload-label">
                            点击选择图片或将图片拖拽到此区域
                        </label>
                    </div>
                    <div class="help-text">支持JPG、PNG、GIF、WebP格式，最大5MB，会自动压缩</div>
                    <div id="image-preview" class="image-preview"></div>
                </div>
                
                <div class="form-group">
                    <label for="content">文章内容 <span class="required">*</span></label>
                    <textarea id="content" name="content" class="form-control textarea" 
                              placeholder="请输入文章内容..." required><?php echo escape($article['内容']); ?></textarea>
                    <div class="help-text">支持换行，显示时会自动转换为HTML格式</div>
                    <div class="char-count">字符数：<span id="contentCount">0</span></div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label>选择分类</label>
                        <div class="select-group">
                            <?php foreach ($categories as $category): ?>
                                <div class="select-item">
                                    <input type="checkbox" id="cat_<?php echo $category['id']; ?>" 
                                           name="categories[]" value="<?php echo $category['id']; ?>"
                                           <?php echo in_array($category['id'], $currentCategoryIds) ? 'checked' : ''; ?>>
                                    <label for="cat_<?php echo $category['id']; ?>"><?php echo escape($category['分类名']); ?></label>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <div class="help-text">可以选择多个分类</div>
                    </div>
                    
                    <div class="form-group">
                        <label>选择标签</label>
                        <div class="select-group">
                            <?php foreach ($tags as $tag): ?>
                                <div class="select-item">
                                    <input type="checkbox" id="tag_<?php echo $tag['id']; ?>" 
                                           name="tags[]" value="<?php echo $tag['id']; ?>"
                                           <?php echo in_array($tag['id'], $currentTagIds) ? 'checked' : ''; ?>>
                                    <label for="tag_<?php echo $tag['id']; ?>"><?php echo escape($tag['标签名']); ?></label>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <div class="help-text">可以选择多个标签</div>
                    </div>
                </div>
                
                <div class="form-group">
                    <label>文章选项</label>
                    <div class="checkbox-group">
                        <div class="checkbox-item">
                            <input type="checkbox" id="is_top" name="is_top" value="1" 
                                   <?php echo $article['是否置顶'] ? 'checked' : ''; ?>>
                            <label for="is_top">置顶文章</label>
                        </div>
                        <div class="checkbox-item">
                            <input type="checkbox" id="is_recommend" name="is_recommend" value="1"
                                   <?php echo $article['是否推荐'] ? 'checked' : ''; ?>>
                            <label for="is_recommend">推荐文章</label>
                        </div>
                    </div>
                    <div class="help-text">置顶文章会在首页优先显示，推荐文章会显示推荐标识</div>
                </div>
                
                <div class="form-actions">
                    <button type="submit" name="update_post" class="btn btn-warning">更新文章</button>
                    <a href="articles.php" class="btn btn-secondary">返回管理</a>
                    <a href="../article.php?id=<?php echo $articleId; ?>" class="btn">查看文章</a>
                </div>
            </form>
        </div>
    </div>

    <script>
        // 字符计数功能
        const contentTextarea = document.getElementById('content');
        const contentCount = document.getElementById('contentCount');
        
        function updateCharCount() {
            const count = contentTextarea.value.length;
            contentCount.textContent = count;
        }
        
        contentTextarea.addEventListener('input', updateCharCount);
        
        // 页面加载时初始化计数
        updateCharCount();
        
        // 图片预览功能
        const imageInput = document.getElementById('article_image');
        const imagePreview = document.getElementById('image-preview');
        
        imageInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            
            if (file) {
                // 验证文件大小（5MB）
                if (file.size > 5 * 1024 * 1024) {
                    alert('图片文件太大，最大允许5MB');
                    imageInput.value = '';
                    imagePreview.innerHTML = '';
                    return;
                }
                
                // 验证文件类型
                const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
                if (!allowedTypes.includes(file.type)) {
                    alert('不支持的文件类型，只允许JPG、PNG、GIF、WebP格式');
                    imageInput.value = '';
                    imagePreview.innerHTML = '';
                    return;
                }
                
                // 创建图片预览
                const reader = new FileReader();
                reader.onload = function(e) {
                    imagePreview.innerHTML = `
                        <img src="${e.target.result}" alt="新图片预览">
                        <br>
                        <span class="remove-image" onclick="removeImage()">× 移除新图片</span>
                        <p style="margin: 5px 0; color: #666; font-size: 12px;">新选择的图片（将替换当前图片）</p>
                    `;
                };
                reader.readAsDataURL(file);
            } else {
                imagePreview.innerHTML = '';
            }
        });
        
        // 移除图片预览
        function removeImage() {
            imageInput.value = '';
            imagePreview.innerHTML = '';
        }
    </script>
</body>
</html> 